package com.kepler.social.web.comp;

import com.kepler.social.common.constants.BusinessState;
import com.kepler.social.common.constants.TipsConst;
import com.kepler.social.common.utils.Jackson2Helper;
import com.kepler.social.common.utils.ServletUtils;
import com.kepler.social.web.common.HttpResult;
import com.kepler.social.service.vo.LoginUser;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;
import java.util.Objects;

@Configuration
public class SSOLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (!Objects.isNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志 可以写入用户的日志
        }
        ServletUtils.renderString(response, Jackson2Helper.toJsonString(new HttpResult(BusinessState.OK.code,
                TipsConst.login_out_success)));
    }
}
